/**
 * jquery 扩展
 */
(function ($) {

    //信息弹出框
    var _message;
    var _timer;
    $.message = function () {
        var setting = {s: 2000, e: "success", c: ""}
        var cnf = {};
        if ($.isPlainObject(arguments[0])) {
            cnf = $.extend({}, setting, arguments[0]);
        } else if (typeof arguments[0] == "string" && typeof arguments[1] == "string") {
            cnf.e = arguments[0];
            cnf.c = arguments[1];
            cnf.s = 1700;
        } else {
            return false;
        }

        if (cnf.e == null || cnf.c == null) {
            return false;
        }

        if (_message == null) {
            _message = $("body").prepend('<div class="align"><div class="mess"><div class="pic"></div><p></p></div></div>').children("div:first");
        }

        function tstart() {
            clearTimeout(_timer);
            _timer = setTimeout(function () {
                _message.fadeOut();
            }, cnf.s);
        }

        clearTimeout(_timer);
        _message.find("div.pic").removeClass("mess_success mess_warn mess_error");

        _message.css({
                left: ($(window).width() - 228) / 2 + 'px',
                top: (($(window).height() - 49) / 2 * 0.4 + $(document).scrollTop()) + 'px'
            })
            .find("div.pic").addClass("mess_" + cnf.e).end()
            .slideDown("fast")
            .hover(function () {
                clearTimeout(_timer)
            }, function () {
                tstart()
            }).find("p").html(cnf.c);

        tstart();
    }

    //异步
    $(document).ajaxComplete(function (event, response, settings) {
        var loginStatus = response.getResponseHeader("loginStatus");
        var tokenStatus = response.getResponseHeader("tokenStatus");

        if (loginStatus == "accessDenied") {
            $.message("warn", "登录超时，请重新登录");
            setTimeout(function () {
                location.reload(true);
            }, 2000);
        } else if (loginStatus == "unauthorized") {
            $.message("warn", "对不起，您无此操作权限！");
        } else if (tokenStatus == "accessDenied") {
            var token = getCookie("token");
            if (token != null) {
                $.extend(settings, {
                    global: false,
                    headers: {token: token}
                });
                $.ajax(settings);
            }
        }
    });
})(jQuery);

$(document).ready(function () {
    //修改默认验证规则
    if($.validator){
        $.validator.setDefaults({
            errorElement: "p",
            errorClass: "perror",
            ignore: "",
            createErrorElement: function (error) {
                var msg = error.html();
                error.html("");
                error.append($("<span></span>").addClass("error"));
                error.append($("<span></span>").addClass("err-mess").html(msg));
                return error;
            },
            errorPlacement: function (error, element) {
                //$(element).siblings("i.desc").hide();
                this.createErrorElement(error).insertAfter(element);
            },
            submitHandler: function (form) {
                $(form).find(":submit").prop("disabled", true);
                form.submit();
            }
        });
    }

    //下拉选中
    $("select[_value]").each(function () {
        $(this).val($(this).attr("_value"));
    });

    //单选选中
    var radioConfig = $(document.body).attr("radioConfig");
    if (radioConfig != undefined && radioConfig != "") {
        var confObj = $.parseJson(radioConfig);
        if (confObj != null) {
            for (var n in confObj) {
                $("input[type='radio'][name='" + n + "'][value='" + confObj[n] + "']").prop("checked", true);
            }
        }
    }

    //返回上一页
    var _backButton = $("#backButton");
    _backButton.click(function () {
        location.href = document.referrer;
        return false;
    });

    //提示title
    if ($.tools != null) {
        var $title = $("#inputForm :input[title], #inputForm label[title]");
        // 表单提示
        $title.tooltip({
            position: "center right",
            offset: [0, 4],
            effect: "fade"
        });
    }

    // 内容点击事件，layer.tips层显示内容
    $("a[class='tips']").click(function () {
        layer.tips($(this).attr("data-value"), this, {
            guide:2,
            time: 3,
            style: ['background-color:#e3f4f9; color:#838383;', '#e3f4f9']
        });
    });

});

//自动切换筛选
function _toggleFilter(bar) {
    var bar = $(bar), itms = bar.nextAll("dl");
    itms.stop().slideToggle(200, "easeOutQuint", function () {
        var d;
        if (bar.hasClass('toggle')) d = bar;
        else d = bar.prev();
        if (itms.is(":visible")) {
            d.removeClass('showIco');
        } else d.addClass('showIco');
    });
}

//图片选择 - 文本编辑器
function imageSelectEditor(name) {
    if (window.imageSelect_editor == undefined) {
        window.imageSelect_editor = UE.getEditor($(document.body).append('<div style="display:none;"><textarea id="imageSelectEditor"></textarea></div>').find("#imageSelectEditor").get(0));
        window.imageSelect_editor.ready(function () {
            window.imageSelect_editor.addListener('beforeInsertImage', function (t, arg) {
                $("[name='" + window.imageSelect_name + "']").val(arg[0].src);
                $(".view-image[uploadview='" + window.imageSelect_name + "']").show().children().attr("src", arg[0].src);
                return false;
            });
        });
        setTimeout(function () {
            imageSelectEditor(name)
        }, 200);
        return false;
    }
    window.imageSelect_name = name;
    window.imageSelect_editor.getDialog("insertimage").open();
}
/**
 * 提示
 * @param msg msg提示内容
 * @param w width+px
 * @param h height+px
 * @param href 点击确定回调函数，非必须
 * @return
 * 2017-06-30
 */

function showHint(msg, w, h, href) {
    return showLayerHint({dialog: {msg : msg, btns: 2,type: -1,yes: function(index){ $('.xubox_yes').hide();layer.load('请稍后');layer.close(index);window.location = href}},width:w,height:h});
}
/**
 * 提示
 * c:config配置对象
 * 2017-06-30
 */
function showLayerHint(c) {

    var setting = {
        shade: [0.5, '#EEE'],
        area: [c.width, c.height],
        border: [1, 1, '#ccc'],
        title: ['提示', "background:#FF4242;color:#FFFFFF;"],
        btn: ['确定','取消'],
    };
    return $.layer($.extend(setting,c));

}

/**
 * 页面层
 * @param t title
 * @param ht html
 * @param w width+px
 * @param h height+px
 * @return
 * 2017-06-26
 */

function showPage(t, ht, w, h) {
    return showLayerPage({title: t,page: {html : ht},width:w,height:h});
}
/**
 * 页面层
 * c:config配置对象
 * 2017-06-26
 */
function showLayerPage(c) {

    var setting = {
        type: 1,
        shade: [0.5, '#EEE'],
        area: [c.width, c.height],
        border: [1, 1, '#ccc'],
        title: ['', "background:#FF4242;color:#FFFFFF;"]
    };
    if(!$.isArray(c.title)) {
        c.title = [c.title,setting.title[1]];
    }
    return $.layer($.extend(setting,c));

}
/**
 * 利用layer弹出层
 * @param t title
 * @param u url
 * @param w width+px
 * @param h height+px
 * @return
 */
function showLWin(t, u, w, h) {
    return showLayerWin({title: t, iframe: {src: u}, area: [w, h]});
}

/**
 * 弹出layer层
 * c:config配置对象
 */
function showLayerWin(c) {
    var setting = {
        type: 2,
        shade: [0.5, '#EEE'],
        border: [1, 1, '#ccc'],
        fix: false,
        title: ["", "background:#FF4242;color:#FFFFFF;"],
        maxmin: false
    }
    if(!$.isArray(c.title)) {
        c.title = [c.title,setting.title[1]];
    }
    return $.layer($.extend(setting,c));
}

//添加Cookie
function addCookie(name, value, options) {
    if (arguments.length > 1 && name != null) {
        if (options == null) {
            options = {};
        }
        if (value == null) {
            options.expires = -1;
        }
        if (typeof options.expires == "number") {
            var time = options.expires;
            var expires = options.expires = new Date();
            expires.setTime(expires.getTime() + time * 1000);
        }
        document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires ? "; expires=" + options.expires.toUTCString() : "") + (options.path ? "; path=" + options.path : "") + (options.domain ? "; domain=" + options.domain : ""), (options.secure ? "; secure" : "");
    }
}

// 获取Cookie
function getCookie(name) {
    if (name != null) {
        var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
        return value ? decodeURIComponent(value[1]) : null;
    }
}

// 移除Cookie
function removeCookie(name, options) {
    addCookie(name, null, options);
}

/**
 * 验证函数
 * @param form选择器
 * @param o 校验规则对象
 * @return
 */
function validateForm(form, o) {
    var setting = {
        errorPlacement: function (error, element) {
            $(element).siblings("i.desc").hide();
            error.insertAfter(element);
        }
    }
    o = $.extend(true, setting, o);
    $(form).validate(o);
}
